<?php
/**
 * --------------------------------------------------------------
 * 手册文档模型
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\model;

use think\Model;

class ManualDoc extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 获取手册的文档树
     * @param int $manual_id
     * @return array
     */
    public function getProjectTree($manual_id)
    {
        if(empty($manual_id)){
            return [];
        }
        
        $tree      = $this::where('manual_id', $manual_id)->field('id,doc_name,pid')->order('id asc,sort ASC')->select();
        $jsonArray = [];

        if(empty($tree) === false){
            foreach ($tree as &$item){
                $tmp['id']     = $item->id.'';
                $tmp['text']   = $item->doc_name;
                $tmp['parent'] = ($item->pid == 0 ? '#' : $item->pid).'';

                $jsonArray[] = $tmp;
            }
        }
        return $jsonArray;
    }
    
    /**
     * 删除文档，包括子文档
     * @param integer $id
     */
    public function deleteDocument($id)
    {
        $documents = [];
        $ids       = [];
        $this_doc  = $this::where('id', $id)->field('id')->find();
        if (empty($this_doc) === false) {
            $documents[] = $this_doc;
            $recursion   = function ($id, $callback) use (&$documents) {
                $docs_id = $this::where('pid', $id)->field('id')->select();

                foreach ($docs_id as $temp_doc) {
                    $documents[] = $temp_doc;
                    $callback($temp_doc['id'], $callback);
                }

            };
            $recursion($this_doc['id'], $recursion);
        }
        foreach ($documents as $document){
            $document->delete();
            $ids[] = $document['id'];
        }
        return empty($ids) ? true : $ids;
    }
}